<template>
	<view class="landlord-container">
		<view class="container-box">
			<view class="container-center">
				<view class="cotent-up">
					<view class="content-title">
						<view style="display: inline-block;width: 30rpx;"></view>门锁列表
					</view>
				</view>
				<view style="height: 40px;"></view>
				<view class="content">
					<view v-if="lockList.length > 0" class="content-top">
						<view v-for="(item, index) in lockList" :key="index" class="lock_item">
							<view class="lock_info">
								<view class="lock_info_l">
									<view class="lock_info_top">
										{{ item.lockName||item.roomName||'' }}
									</view>
									<view class="lock_info_center">
										<electric-quantity :ElectricQuantity="item.batteryPercentage*1"></electric-quantity>
										<text class="idnum">NO.{{ item.lockNo||item.roomNo||'' }}</text>
									</view>
									<view class="lock_info_bottom">
										<text class="enddate">到期日期：{{item.endTime.slice(0,16)}}</text>
									</view>
								</view>
								<view class="lock_info_r">
									<view @click="openLock(item)">
										<image class="lock_img" src="@/static/room/lock.png" mode="aspectFit"></image>
										<view>点击开锁</view>
									</view>
								</view>
							</view>
						</view>
						<view style="height: 60rpx;">
						</view>
					</view>
					<view v-else class="noInformation">
						<view class="no-content">
							<image style="width: 222rpx; height: 146rpx;" src="@/static/room/nocontent.png" mode="aspectFit"></image>
							<text class="no-num">暂无门锁</text>
						</view>
					</view>
					<view style="height: 65px;"></view>
				</view>
			</view>
			<!-- <image style="width: 180rpx; height: 180rpx;" src="../../static/index/addlock.png" mode="aspectFit"
				@click="addLock"></image> -->
		</view>
	</view>
</template>

<script>
	import util from '@/utils/util.js';
	import bleUtils from '@/utils/BleUtils.js';
	import {
		getlockList,
		sendOpenRec,
		getOpenLockCmd,
		getHotelLockList,
		remoteOpenHotelLock,
		remoteOpenHotelLockReply
	} from '@/api/lock.js'
	import {
		mapState
	} from 'vuex'
	import tabBar from '@/components/tab-bar/tab-bar.vue'
	export default {
		components: {
			tabBar
		},
		data() {
			return {
				showLoading: true,
				lockNo: '',
				userId: '', // 用户id
				userMob: '', // 当前用户手机号
				lockList: [],
				replyMsg: '', // 命令的回复数据
				cmdLen: 0, // 命令的字节长度				
				lockType: '',
				curLock: null, // 当前锁的信息
				timer: null, // 开锁超时的定时器
				timeout: 15000, // 开锁20秒 未响应属于超时
			}
		},
		onUnload() {
			// 关闭蓝牙连接
			bleUtils.closeBLEConnection();
			// 关闭蓝牙适配器
			bleUtils.closeBluetoothAdapter();
		},
		onShow(options) {
			this.userMob = this.$userInfo.mobile;
			this.userId = this.$userInfo.userId;
			this.getLockListInfo();
		},
		methods: {
			// 下拉刷新
			onPullDownRefresh() {
				this.getLockListInfo();
			},
			containsNumber(str) {
				var reg = /\d/;
				return reg.test(str);
			},
			// 获取锁列表
			async getLockListInfo() {
				try {
					this.lockList = []
					if (this.userMob == null || this.userMob == '' || this.userId == null || this.userId ==
						"") { //用户没有登录
						return
					}
					let params = {
						mobile: this.userMob,
					}

					const res = await Promise.all([getlockList(params), getHotelLockList(params)])
					this.showLoading = false;
					res.forEach((item) => {
						if (item && item.statecode === '0') {
							this.lockList = [...this.lockList, ...item.data]
						}
					})
					// let res = await getlockList(params);
					// console.log('index getLockListInfo resp-->' + JSON.stringify(res))
					// if (res && res.statecode === '0') {
					// 	this.lockList = res.data || []
					// } else {
					// 	util.toast(res.statemsg);

					// }
					uni.stopPullDownRefresh();
				} catch (err) {
					this.showLoading = false;
					util.toast(err.message)
				}
			},
			// 前往开锁页面
			goToSigleLock(item) {
				console.log('点击的锁===>', item)
				this.$store.commit('setLockInfo', item)
				uni.navigateTo({
					url: '/pages/common/singleLock/singleLock'
				});
			},
			//新增门锁
			addLock() {
				if (!this.userMob) { // 是否存在用户手机号
					uni.showModal({
						title: '温馨提示',
						content: '请先登录',
						showCancel: false,
						confirmText: '确认',
						success: (res) => {
							if (res.confirm) {
								this.goLogin()
							}
						}
					})
					return;
				}
				uni.navigateTo({
					url: '/pages/landlord/addlock/addLockScan'
				})
			},
			// 执行蓝牙开锁
			async openLock(item) {
				this.lockType = item.lockType || '';
				this.curLock = item;
				if (this.lockType == 'HOTEL') {
					this.scanHotelLock(item)
				} else {
					this.openApartmentLock(item)
				}
			},
			async scanHotelLock(item) {
				try {
					util.loading('扫描广播');
					if (this.timer) clearTimeout(this.timer)
					this.timer = setTimeout(() => {
						util.hideLoading();
						bleUtils.closeBluetoothAdapter();
						util.alert('开锁超时!');
					}, this.timeout)
					await bleUtils.openBluetoothAdapter();
					// 先监听
					uni.onBluetoothDeviceFound((res) => {
						const device = res.devices[0];
						const name = device.localName || device.name || '';
						// if (name) console.log('device name ', name.toLowerCase(),name.toLowerCase().includes('es_'))
						if (name && name.toLowerCase().includes('es_')) {
							const advertisData = device.advertisData;
							// console.log('found device advertisData===>', advertisData)
							if (advertisData) {
								const deviceId = device.deviceId;
								const advertisHex = util.ab2hex(advertisData);
								const power = parseInt(advertisHex.substr(16, 2), 16); // 16进制转10进制
								const mac = advertisHex.substr(18, 12);
								const hotelUid = advertisHex.substr(-20, 10);
								const roomNoArr = advertisHex.substr(-10, 8).split('');
								const roomNo = roomNoArr.splice(0, 6).join('') + roomNoArr[roomNoArr.length - 1] + roomNoArr[roomNoArr.length - 2];
								if (hotelUid == item.hotelUid && roomNo == item.roomNo) {
									console.log('found device advertisData===>', advertisHex);
									uni.stopBluetoothDevicesDiscovery({
										success() {
											console.log('蓝牙停止发现')
										}
									})
									// 走开锁流程
									item.mac = mac;
									this.openHotelLock(item, deviceId);
								}
							}
						}
					})
					// 然后开启搜索
					uni.startBluetoothDevicesDiscovery({
						allowDuplicatesKey: false,
						success: (res) => {
							console.log('startBluetoothDevicesDiscovery success')
						},
						fail: (res) => {
							if (this.timer) clearTimeout(this.timer)
							util.hideLoading();
							util.toast('发现失败!')
						}
					})
				} catch (e) {
					if (this.timer) clearTimeout(this.timer)
					util.hideLoading()
					util.toast('请开启蓝牙并赋予定位权限!');
				}
			},
			async openHotelLock(item, deviceId) {
				try {
					util.loading('开锁中...');
					if (!this.$sysInfo.locationEnabled) {
						util.hideLoading();
						util.alert('请先开启手机GPS定位服务!');
						return;
					}
					if (!this.$sysInfo.locationAuthorized) {
						// 让用户授权开启定位服务 为了让老版本的安卓手机能使用蓝牙
						await bleUtils.doAuthorize('scope.userLocation')
					}
					// 酒店锁的开锁
					this.replyMsg = '';
					this.lockNo = item.lockNo;
					let resp = await remoteOpenHotelLock({
						cardId: item.cardId,
						lockType: 'HOTEL',
						roomId: item.roomId,
						mac: item.mac
					});
					if (resp && resp.statecode == '0' && resp.data.taskMessage) {
						console.log('device deviceId ->', deviceId)
						this.curLock.recordId = resp.data.recordId;
						await bleUtils.openBluetoothAdapter();
						await bleUtils.createBLEConnection(deviceId);
						await bleUtils.notifyBLECharacteristicValueChange(deviceId);
						// 监听当特征值发生变化的回调
						bleUtils.onBLECharacteristicValueChange((res) => {
							this.receiveBleData(res)
						});
						const cmdMsg = resp.data.taskMessage;
						if (cmdMsg && cmdMsg.trim()) {
							// const cmd_buffer = bleUtils.myStringtoHex(cmdMsg);
							// console.log('send cmd-->', cmdMsg)
							const cmdByteLen = cmdMsg.trim().length / 2;
							this.sendPacket(cmdMsg, cmdByteLen);
						}
					} else {
						util.loading('开锁中...');
						util.alert('获取开锁命令失败!');
					}
				} catch (err) {
					console.log('openHotelLock err', err)
					if (this.timer) clearTimeout(this.timer)
					util.hideLoading();
					util.infotip(err.errCode);
					// 关闭蓝牙连接
					bleUtils.closeBluetoothAdapter();
				}
			},
			async openApartmentLock(item) {
				try {
					util.loading('开锁中...');
					if (this.timer) clearTimeout(this.timer)
					this.timer = setTimeout(() => {
						util.hideLoading();
						bleUtils.closeBluetoothAdapter();
						util.alert('开锁超时!');
					}, this.timeout)
					if (!this.$sysInfo.locationEnabled) {
						if (this.timer) clearTimeout(this.timer)
						util.hideLoading();
						util.alert('请先开启手机GPS定位服务!');
						return;
					}
					if (!this.$sysInfo.locationAuthorized) {
						// 让用户授权开启定位服务 为了让老版本的安卓手机能使用蓝牙
						await bleUtils.doAuthorize('scope.userLocation')
					}
					// 公寓锁的开锁
					this.replyMsg = '';
					this.lockNo = item.lockNo;
					let resp = await getOpenLockCmd({
						lockNo: item.lockNo,
						isOpen: true,
						mobile: this.userMob
					});
					if (resp && resp.statecode == '0' && resp.data.taskMessage) {
						let cmdMsg = resp.data.taskMessage;
						if (cmdMsg && cmdMsg.trim()) {
							cmdMsg = cmdMsg.trim();
							this.openLockByMac(item.mac, cmdMsg)
						}
					} else {
						if (this.timer) clearTimeout(this.timer)
						util.hideLoading();
						util.alert('获取开锁命令失败!');
					}
				} catch (err) {
					console.log('bluetooth err--->', err)
					if (this.timer) clearTimeout(this.timer)
					util.hideLoading();
					util.infotip(err.errCode);
					// 关闭蓝牙
					bleUtils.closeBluetoothAdapter();
				}
			},
			async openLockByMac(mac, cmdMsg) {
				try {
					const formatMac = util.strInsert(mac, 2);
					await bleUtils.openBluetoothAdapter();
					await bleUtils.waitBleConnAndNotify(mac, formatMac);
					// 监听当特征值发生变化的回调
					bleUtils.onBLECharacteristicValueChange((res) => {
						this.receiveBleData(res)
					});
					// const cmd_buffer = bleUtils.myStringtoHex(cmdMsg);
					const cmdByteLen = cmdMsg.length / 2;
					this.sendPacket(cmdMsg, cmdByteLen);
				} catch (e) {
					if (this.timer) clearTimeout(this.timer)
					util.hideLoading();
					console.log('openLockByMac err--->', err)
					bleUtils.closeBluetoothAdapter();
				}

			},
			// 发送数据包给蓝牙设备
			async sendPacket(cmdData, size, offset = 0) {
				try {
					do {
						const step = offset + 20 > size ? size - offset : 20;
						console.log('offset', offset, 'step', step, 'size', size)
						const cmd = cmdData.substr(offset * 2, step * 2);
						console.log("--->write data:" + cmd);
						const hex = bleUtils.myStringtoHex(cmd);
						const uint8Array = new Uint8Array(hex);
						const data = uint8Array.buffer;
						await bleUtils.writeBLECharacteristicValue(data);
						offset += step;
					} while (offset < size)
				} catch (err) {
					if (this.timer) clearTimeout(this.timer)
					util.hideLoading();
					util.infotip(err.errCode);
					// 关闭蓝牙连接
					bleUtils.closeBluetoothAdapter();
				}
			},
			receiveBleData(res) {
				try {
					this.replyMsg += res;
					console.log('replyMsg res==>', this.replyMsg)
					const header = res.substr(0, 4).toUpperCase();
					if (header == '55AA') {
						this.cmdLen = parseInt(res.substr(4, 4), 16) * 2 + 8;
						console.log('replyMsg.length', this.replyMsg.length, ' cmdLen', this.cmdLen)
						if (this.replyMsg.length == this.cmdLen) {
							const code = this.replyMsg.substr(-6, 2);
							if (this.lockType == 'HOTEL') {
								remoteOpenHotelLockReply({
									'recordId': this.curLock.recordId,
									'lockMac': this.curLock.mac.toUpperCase(),
									'replyCode': code
								}).then((resp) => {
									console.log('remoteOpenHotelLockReply resp', resp)
								}).catch((err) => {
									console.log('remoteOpenHotelLockReply err', err)
								})
							} else {
								sendOpenRec({
									'lockNo': this.lockNo,
									'recordId': this.curLock.recordId,
									'replyMessage': this.replyMsg.toUpperCase(),
									'replyCode': code
								}).then((resp) => {
									console.log('/lock/unlockManage/reply resp', resp)
								}).catch((err) => {
									console.log('/lock/unlockManage/reply err', err)
								})
							}
							util.hideLoading();
							if (code == '00') {
								util.toast('开锁成功!');
							} else {
								util.toast('开锁失败!');
							}
						}
					}
				} catch (err) {
					console.log(err)
				} finally {
					if (this.timer) clearTimeout(this.timer)
					util.hideLoading();
					bleUtils.closeBluetoothAdapter();
				}
			},
			// 登录
			goLogin() {
				uni.navigateTo({
					url: '/pages/main/login/codelogin'
				})
			}
		}
	}
</script>
<style>
	page {
		background-color: #3E8EFF;
	}
</style>
<style lang="scss" scoped>
	.landlord-container {
		height: 100%;
		width: 100%;

		.loading {
			margin: 50% auto;
		}

		// overflow: hidden;

		.container-box {
			height: 100vh;
			// overflow: auto;
			// padding: 0 60rpx;
			box-sizing: border-box;
			background: #F3F4FC;

			.add-box {
				position: fixed;
				bottom: 120rpx;
				right: 10rpx;
			}

			.login-tip {
				width: 100%;
				height: 60rpx;
				line-height: 60rpx;
				background: rgba(29, 120, 247, 0.3);
				color: #FFFFFF;
				padding: 0 10rpx;
				box-sizing: border-box;
				border-radius: 6rpx;
				font-size: 24rpx;

				.login-tap {
					color: #1D78F7;
				}
			}

			.container-center {

				display: flex;
				flex-direction: column;


				.cotent-up {
					background: #3E8EFF;
					width: 100%;
					padding: 30rpx 0rpx 0rpx 0rpx;
					align-items: center;
					// margin-top: 60rpx;
					// background-color: #00be50;
					position: fixed;
					top: 0px;
					z-index: 12;

					.content-title {
						color: #1F2642;
						font-size: 40rpx;
						font-weight: bold;
						// margin-bottom: 30rpx;					
						width: 100%;
						height: 50px;
						line-height: 50px;
						border-top-left-radius: 40rpx;
						border-top-right-radius: 40rpx;
						background: #F3F4FC;
					}

					.content-icon {
						display: flex;
						flex-direction: row;
						justify-content: right;
						align-items: center;

						// background-color: #00be50;
						.content-icon-title {
							color: #4C5168;
							font-size: 28rpx;
							margin-left: 12rpx;
							// margin-right: 48rpx;
							line-height: 32rpx;
						}


					}
				}

				.content {
					display: flex;
					flex-direction: column;
					padding: 30rpx 32rpx;
					background: #F3F4FC;
					min-height: 100vh-12;

					.no_login_content {
						text-align: center;
						position: relative;
						background: transparent;
						z-index: 8;
						margin-top: 35%;

						.no_login_info {
							color: #8F92A0;

							.no_login_desc {
								margin: 10px 0px;
							}
						}

						.btn {
							width: 30%;
							margin: 20rpx auto;
							font-size: 30rpx;
							padding: 18rpx 20rpx;
							background: linear-gradient(135deg, #4593FF 0%, #1C78F7 100%);
							color: #fff;
							border-radius: 40rpx;
							text-align: center;
						}
					}

					.content-top {
						margin-top: 10rpx;
						overflow: auto;

						.lock_item {
							position: relative;

							.lock_info {
								padding: 24rpx 24rpx;
								margin: 20rpx 0;
								position: relative;
								border-radius: 20rpx;
								background-color: #fff;
								display: flex;
								flex-direction: row;
								flex-wrap: nowrap;
								justify-content: space-between;
								align-items: center;

								.lock_info_l {
									.lock_info_top {
										color: #1F2642;
										font-size: 36rpx;
										font-weight: bold;
										width: 80%;
										overflow: hidden;
										text-overflow: ellipsis;
										display: -webkit-box;
										-webkit-line-clamp: 2;
										-webkit-box-orient: vertical;
									}

									.lock_info_center {
										display: flex;
										margin: 32rpx 0 24rpx 0;

										.idnum {
											color: #8F92A0;
											font-size: 28rpx;
											margin-left: 16rpx;
										}
									}

									.lock_info_bottom {
										color: #8F92A0;
										font-size: 28rpx;
										width: 100%;
										display: flex;
										justify-content: space-between;

										.enddate {
											display: block;
										}
									}
								}

								.lock_info_r {
									display: flex;
									flex-direction: column;
									justify-content: center;
									align-items: center;
									height: 100%;
									text-align: center;
									color: #3E8EFF;

									.lock_img {
										width: 80rpx;
										height: 80rpx;
										border: 1px solid #cccccc78;
										border-radius: 10px;
									}
								}

							}

							.rent_status {
								position: absolute;
								top: 0;
								right: 0;
								width: 128rpx;
								height: 64rpx;
								border-top-right-radius: 20rpx;
								border-bottom-left-radius: 20rpx;
								text-align: center;
								line-height: 65rpx;
							}

							.color1 {
								background-color: #e5f1ff;
								color: #2A7FF5;
							}

							.color2 {
								background-color: #e6f7ed;
								color: #00be50;
							}

							.color3 {
								background-color: #ffeae9;
								color: #ff3d3d;
							}
						}

						.lock_min {
							flex-wrap: wrap;
							display: inline-block;

							// align-content: space-between;
							// background-color: #00be50;
							.lock_min_back {
								height: 164rpx;
								border-radius: 24rpx;
								background: #FFFFFF;
								margin-right: 15rpx;
								margin-top: 20rpx;
								position: relative;
							}

							.lock_min_reback {
								height: 164rpx;
								border-radius: 24rpx;
								background: #FFFFFF;
								margin-right: 0rpx;
								margin-left: 20rpx;
								margin-top: 20rpx;
								position: relative;
							}

							.lock_min_title {
								color: #1F2642;
								font-size: 36rpx;
								// align-items :center;
								font-weight: bold;
								line-height: 44rpx;
								top: 72rpx;
								margin-left: 30rpx;
								position: relative;
								word-break: keep-all;
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
							}
						}

					}
				}

				.noInformation {
					height: calc(100vh - 350rpx);

					.no-content {
						display: flex;
						flex-direction: column;
						align-items: center;
						padding: 240rpx 0;

						.no-num {
							font-size: 28rpx;
							color: #8F92A0;
							margin-top: 30rpx;
						}
					}
				}
			}
		}

		.popup-box {
			background: #fff;
			width: 40vh;
			border-radius: 20rpx;
			padding: 100rpx 50rpx 50rpx 50rpx;
			text-align: center;
			color: #1F2642;
			font-size: 32rpx;

			.btn-box {
				background: #4593FF;
				margin-top: 80rpx;
			}

			.btn-view {
				display: flex;
				flex-direction: row;
				justify-content: space-around;
				margin-top: 80rpx;
				font-size: 36rpx;

				.btn-left {
					margin-right: 10rpx;
					background: #fff;
					color: #1D78F7;
					width: 45%;
					border: 2rpx solid #1D78F7;
				}

				.btn-right {
					margin-left: 10rpx;
					background: #4593FF;
					color: #fff;
					width: 45%;
				}
			}

		}
	}
</style>